package com.shopping.mall.core.module.goodData.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shopping.mall.base.util.DateUtils;
import com.shopping.mall.core.module.cart.entity.Cart;
import com.shopping.mall.core.module.goodData.entity.GoodData;
import com.shopping.mall.core.module.goodData.entity.GoodDataQueryVO;
import com.shopping.mall.core.module.goodData.mapper.GoodDataMapper;
import com.shopping.mall.core.module.goodData.service.GoodDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shopping.mall.base.http.ResponseState;
import com.shopping.mall.base.http.Result;
import com.shopping.mall.base.util.WrapperUtils;
import com.shopping.mall.core.module.goods.entity.Goods;
import com.shopping.mall.core.module.goods.mapper.GoodsMapper;
import com.shopping.mall.core.module.order.entity.Order;
import com.shopping.mall.core.module.saleData.entity.SaleData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.List;
/**
 * <p>
 *  GoodData服务实现类
 * </p>
 *
 * @author zzy
 * @since 2021-09-02
 */
@Validated
@Service
public class GoodDataServiceImpl extends ServiceImpl<GoodDataMapper, GoodData> implements GoodDataService {

    @Autowired
    private GoodDataMapper goodDataMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 分页查询
     * @param current ：页码
     * @param size ：每页条数
     * @param goodDataQueryVO ：筛选条件
     * @return IPage<GoodData>
     */
    @Override
    public IPage<GoodData> getGoodDataPage(Integer current, Integer size, GoodDataQueryVO goodDataQueryVO){
        Integer visitAll=goodDataMapper.getVisitAll(goodDataQueryVO);
        Integer total=goodDataMapper.getTotal(goodDataQueryVO);
        List<GoodData> records=goodDataMapper.getPage((current-1)*size,size,goodDataQueryVO);
        System.out.println("total"+total);
        if(records!=null&&records.size()>0){
            for(GoodData goodData:records){
                if(visitAll!=null&&visitAll!=0){
                    goodData.setVisitRate(goodData.getVisitNum()/(double)visitAll);
                }else {
                    goodData.setVisitRate(0.0);
                }
            }
        }
        IPage<GoodData> goodDataPage = new Page<>(current,size);
        goodDataPage.setTotal(total);
        goodDataPage.setPages(total/size);
        goodDataPage.setRecords(records);
        return goodDataPage;
    }

    /**
     * 查询所有
     * @param goodDataQueryVO ：筛选条件
     * @return List<GoodData>
     */
    @Override
    public List<GoodData> getAll(GoodDataQueryVO goodDataQueryVO){
        Integer visitAll=goodDataMapper.getVisitAll(goodDataQueryVO);
        QueryWrapper<GoodData> queryWrapper = WrapperUtils.queryWrapperByQueryVONoTime(goodDataQueryVO);
        if(goodDataQueryVO.getBefore()!=null){
            queryWrapper.ge("date",goodDataQueryVO.getBefore());
        }
        if(goodDataQueryVO.getAfter()!=null){
            queryWrapper.le("date",goodDataQueryVO.getAfter());
        }
        List<GoodData> goodDataList=goodDataMapper.selectList(queryWrapper);
        for(GoodData goodData:goodDataList){
            goodData.setVisitRate(goodData.getVisitNum()/(double)visitAll);
        }
        return goodDataList;
    }

    /**
     * 通过id删除
     * @param id：goodDataId
     * @return Result<Object>
     */
    @Override
    public Result<Object> deleteById(String id){
        GoodData goodData=goodDataMapper.selectById(id);
        if(goodData==null){
            return Result.error(ResponseState.TARGET_NOT_EXIST.getValue(), ResponseState.TARGET_NOT_EXIST.getMessage());
        }
        goodDataMapper.deleteById(id);
        return Result.OK();
    }

    /**
    * 批量删除
    * @param ids：id列表
    * @return Result<Object>
    */
    @Override
    public Result<Object> batchDelete(List<String> ids){
        UpdateWrapper<GoodData> updateWrapper=new UpdateWrapper<>();
        updateWrapper.in("id",ids);
        goodDataMapper.delete(updateWrapper);
        return Result.OK();
    }

    /**
     * 商品访问
     */
    @Override
    public void addVisit(GoodData goodData) {
        boolean isFirst=false;
        try {
            Timestamp today= DateUtils.getTodayTimestamp();
            QueryWrapper<GoodData> goodDataQueryWrapper=new QueryWrapper<>();
            goodDataQueryWrapper.eq("good_id",goodData.getGoodId());
            goodDataQueryWrapper.eq("specification_id",goodData.getSpecificationId());
            goodDataQueryWrapper.eq("date",today);
            GoodData oldGoodData=goodDataMapper.selectOne(goodDataQueryWrapper);
            if(oldGoodData==null){
                oldGoodData=goodData;
                oldGoodData.setDate(today);
                isFirst=true;
                Goods good=goodsMapper.selectById(oldGoodData.getGoodId());
                oldGoodData.setGoodName(good.getName());
            }
            oldGoodData.setVisitNum(oldGoodData.getVisitNum()+1);
            oldGoodData.setConvertRate(oldGoodData.getOrderGoodsNum()/(double)oldGoodData.getVisitNum());
            if(isFirst){
                goodDataMapper.insert(oldGoodData);
            }else {
                goodDataMapper.updateById(oldGoodData);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }


    /**
     * 下单
     * @param order
     */
    @Override
    public void addOrder(Order order) throws ParseException {
        Timestamp today = DateUtils.getTodayTimestamp();
        JSONArray jsonArray=JSONArray.parseArray(order.getGoods());
        List<Cart> cartList=jsonArray.toJavaList(Cart.class);
        for(Cart cart:cartList){
            boolean isFirst=false;
            QueryWrapper<GoodData> goodDataQueryWrapper=new QueryWrapper<>();
            goodDataQueryWrapper.eq("good_id",cart.getGoodId());
            goodDataQueryWrapper.eq("specification_id",cart.getGood().getSpecification().getId());
            goodDataQueryWrapper.eq("date",today);
            GoodData oldGoodData=goodDataMapper.selectOne(goodDataQueryWrapper);
            if(oldGoodData==null){
                oldGoodData=new GoodData();
                oldGoodData.setGoodId(cart.getGoodId());
                oldGoodData.setSpecificationId(cart.getGood().getSpecification().getId());
                oldGoodData.setDate(today);
                isFirst=true;
                Goods good=goodsMapper.selectById(oldGoodData.getGoodId());
                oldGoodData.setGoodName(good.getName());
            }
            oldGoodData.setOrderGoodsNum(oldGoodData.getOrderGoodsNum()+cart.getNumber());
            if(oldGoodData.getVisitNum()!=0){
                oldGoodData.setConvertRate(oldGoodData.getOrderGoodsNum()/(double)oldGoodData.getVisitNum());
            }
            oldGoodData.setOrderSale(oldGoodData.getOrderSale()+cart.getPrice()*cart.getNumber());
            if(isFirst){
                goodDataMapper.insert(oldGoodData);
            }else {
                goodDataMapper.updateById(oldGoodData);
            }
        }

    }
}